'''
Created on 14/06/2010

@author: Will
'''

import math
from pymunk import Vec2d
class RearWheel():
        
    def __init__(self,car,world):
            self.car = car
            self.offset = (0,0)
            self.rotation = car.body._get_angle()
            self.position = 0,0
            self.braking = False
            self.world = world

            
    def tryToMoveTo(self,position):
        rotation = self.getRotation() % (2*math.pi)
        velVec = Vec2d(position[0]-self.position[0],position[1] - self.position[1])
        angle =  velVec.get_angle() - rotation
 
        
        mass = self.car.mass
        normal = mass * 15
        maxForcePerWheel = normal/4 * 0.9
        if self.braking:
            self.impulse = -1*velVec.normalized()*maxForcePerWheel
            
            
        else:    
            self.impulse = math.sin(angle)*velVec.get_length()*self.car.mass*10/4
            self.impulse = Vec2d(self.impulse,0).rotated(rotation-math.pi/2)
            
        if self.impulse.get_length() > maxForcePerWheel - 10:
            ratio = maxForcePerWheel/self.impulse.get_length()* 0.8
            self.impulse = self.impulse * ratio
            self.world.spawner.spawnDecal(self.position[0],self.position[1],velVec.get_angle()+math.pi/2)
        
        
        
        impulse2 = self.impulse.x,self.impulse.y
        
        offset = self.car.getRotatedPoint(self.offset)
        
        self.position = position
        self.rotation = self.car.body._get_angle()
        
        self.braking = False
        return impulse2,offset
    
    def getRotation(self):
        return self.rotation + math.pi/2
    